# coding=utf-8

from django.contrib.auth import get_user_model, authenticate

from rest_framework import serializers
from rest_framework_jwt.serializers import JSONWebTokenSerializer
from rest_framework_jwt.settings import api_settings
from apps.log.models import BizLog
from apps.admin import admin_log
from utils import get_remote_addr

User = get_user_model()
jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

class AdminUserJWTSerializer(JSONWebTokenSerializer):
    def validate(self, attrs):
        credentials = {
            self.username_field: attrs.get(self.username_field),
            'password': attrs.get('password')
        }

        if all(credentials.values()):
            user = authenticate(**credentials)

            if user:
                if not user.is_active:
                    msg = u'禁用帐户，禁止登录'
                    admin_log(user, BizLog.INSERT,u'禁用帐户[%s]尝试登录系统,IP[%s]' % (user.username, get_remote_addr(self.request)))
                    raise serializers.ValidationError(msg)

                if not user.is_administrator():
                    msg = u'非管理员账号，禁止登录'
                    admin_log(user, BizLog.INSERT,u'非管理员账号[%s]尝试登录系统,IP[%s]' % (user.username, get_remote_addr(self.request)))
                    raise serializers.ValidationError(msg)

                payload = jwt_payload_handler(user)
                admin_log(user, BizLog.INSERT, u'[%s]登录系统,IP[%s]' % (user.username,get_remote_addr(self.request)))

                return {
                    'token': jwt_encode_handler(payload),
                    'user_id': user.id,
                    'username': user.username
                }
            else:
                msg = u'账号或者密码错误!'
                admin_log(None, BizLog.INSERT, u'登录失败[%s][%s],IP[%s]' % (attrs[self.username_field], attrs['password'], get_remote_addr(self.request)))
                raise serializers.ValidationError(msg)
        else:
            msg = u'必须包含“{username field}”和“password'
            msg = msg.format(username_field=self.username_field)
            raise serializers.ValidationError(msg)
